﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace IMPL.Algorithms
{
    // example from:
    // http://tipsandtricks.runicsoft.com/CSharp/WpfPixelDrawing.html
    class Bitmap
    {
        BitmapSource bitmap;
        PixelFormat pf = PixelFormats.Rgb24;
        int width, height, rawStride;
        byte[] pixelData;
        DispatcherTimer timer;
        Image image1;

        Bitmap(Image image)
        {
            this.image1 = image;
            Init();
        }

        void Init()
        {
            width = (int)image1.Width;
            height = (int)image1.Height;
            rawStride = (width * pf.BitsPerPixel + 7) / 8;
            pixelData = new byte[rawStride * height];
        }

        void SetPixel(int x, int y, Color c, byte[] buffer, int rawStride)
        {
            int xIndex = x * 3;
            int yIndex = y * rawStride;
            buffer[xIndex + yIndex] = c.R;
            buffer[xIndex + yIndex + 1] = c.G;
            buffer[xIndex + yIndex + 2] = c.B;
        }

        void Render()
        {
            for (int y = 0; y < height; y++)
            {
                int yIndex = y * rawStride;
                for (int x = 0; x < rawStride; x += 3)
                {
                    pixelData[x + yIndex] = 0;
                    pixelData[x + yIndex + 1] = 0;
                    pixelData[x + yIndex + 2] = 255;
                }
            }
        }

        void button1_Click(object sender, RoutedEventArgs e)
        {
            Init();
            Task t = Task.Factory.StartNew(Render);
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Tick += UpdateScreen;
            timer.Start();
        }

        void UpdateScreen(object o, EventArgs e)
        {
            bitmap = BitmapSource.Create(width, height,
                96, 96, pf, null, pixelData, rawStride);
            image1.Source = bitmap;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            timer.Stop();
        }
    }
}
